package springSecurity

import org.apache.commons.lang.builder.HashCodeBuilder

class AuthUserSecurityRole implements Serializable {

	AuthUser authUser
	SecurityRole securityRole

	boolean equals(other) {
		if (!(other instanceof AuthUserSecurityRole)) {
			return false
		}

		other.authUser?.id == authUser?.id &&
			other.securityRole?.id == securityRole?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (authUser) builder.append(authUser.id)
		if (securityRole) builder.append(securityRole.id)
		builder.toHashCode()
	}

	static AuthUserSecurityRole get(long authUserId, long securityRoleId) {
		find 'from AuthUserSecurityRole where authUser.id=:authUserId and securityRole.id=:securityRoleId',
			[authUserId: authUserId, securityRoleId: securityRoleId]
	}

	static AuthUserSecurityRole create(AuthUser authUser, SecurityRole securityRole, boolean flush = false) {
		new AuthUserSecurityRole(authUser: authUser, securityRole: securityRole).save(flush: flush, insert: true)
	}

	static boolean remove(AuthUser authUser, SecurityRole securityRole, boolean flush = false) {
		AuthUserSecurityRole instance = AuthUserSecurityRole.findByAuthUserAndSecurityRole(authUser, securityRole)
		if (!instance) {
			return false
		}

		instance.delete(flush: flush)
		true
	}

	static void removeAll(AuthUser authUser) {
		executeUpdate 'DELETE FROM AuthUserSecurityRole WHERE authUser=:authUser', [authUser: authUser]
	}

	static void removeAll(SecurityRole securityRole) {
		executeUpdate 'DELETE FROM AuthUserSecurityRole WHERE securityRole=:securityRole', [securityRole: securityRole]
	}

	static mapping = {
		id composite: ['securityRole', 'authUser']
		version false
	}
}
